package com.example.guarding_jc;

import java.util.List;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;

public class ConnectivityChangeReceiver extends BroadcastReceiver{
	
	@Override
	public void onReceive(Context context, Intent intent){
		ConnectivityManager connectivityManager = (ConnectivityManager)context.getSystemService( Context.CONNECTIVITY_SERVICE );
		NetworkInfo activeNetworkInfor = connectivityManager.getActiveNetworkInfo();
		boolean isConnected = activeNetworkInfor != null && activeNetworkInfor.isConnected();
		if (isConnected){
			//check if there is any pending submission
			//if yes, send all the pending submissions to the server
			
			TosendDataSource datasource = new TosendDataSource(context);
			datasource.open();
	        List<DBEntry> entries = datasource.getAllPendingScans();
	        
	        int numOfPendingReports = entries.size();
	        
	        if (numOfPendingReports > 0){
	        	new SendPendingScans().execute();
	        }
		}
	}
	
	private class SendPendingScans extends AsyncTask<Void, Void, Void>{
		@Override
		protected Void doInBackground(Void...lists ) {
			List<DBEntry> values = Guarding_JC.datasource.getAllPendingScans();
	        for (int i = 0; i < values.size(); i++){
	        	String uid = values.get(i).getUid();
	        	String Mac = values.get(i).getMac();
	        	String sequence = values.get(i).getSeq();
	        	String challenge = values.get(i).getChallenge();
	        	String time = values.get(i).getTime();
	        	String imei = values.get(i).getImei();
	        	
	        	String responseURL = Guarding_JC.URL + "tagResponse/" + uid + "/" + Mac + "/" + sequence + "/" 
	        										+ challenge + "/" + imei + "/" + time;
	        	
	        	Utility.sendToServer(responseURL);
	        	//remove the entry from the db
	        	String id = values.get(i).getId();
	        	Utility.deleteEntry(Guarding_JC.datasource, id);
	        }
			return null;
		}
	}
}
